﻿using Microsoft.EntityFrameworkCore;
using S.Archives.Domain.S.ArchivesDbContext;

namespace S.Archives.Infrstructre
{
    public class BaseRepository<T> : IBaseRepository<T> where T : class
    {
        public ArchivesDbContext db { get; }
     

        public BaseRepository(ArchivesDbContext db)
        {
            this.db = db;
        }

        public bool Add(T t)
        {
            db.Set<T>().Add(t);
            return db.SaveChanges() > 0;
        }

        public bool Delete(int id)
        {
            var list = db.Set<T>().Find(id);
            db.Set<T>().Remove(list);
            return db.SaveChanges() > 0;
        }

        public IQueryable<T> GetAll()
        {
            return db.Set<T>().AsQueryable();
        }

        public bool Update(T t)
        {
            db.Set<T>().Update(t);
            return db.SaveChanges() > 0;
        }

        #region 异步增删改查方法

        public async Task<bool> AddAsync(T t)
        {
            db.Set<T>().AddAsync(t);
            return await db.SaveChangesAsync() > 0;
        }

        public async Task<bool> DeleteAsync(int id)
        {
            var list = await db.Set<T>().FindAsync(id);
            db.Set<T>().Remove(list);
            return await db.SaveChangesAsync() > 0;
        }

        public async Task<bool> UpdateAsync(T t)
        {
            db.Set<T>().Update(t);
            return await db.SaveChangesAsync() > 0;
        }

        public async Task<List<T>> GetAllAsync()
        {
            return await db.Set<T>().ToListAsync();
        }
        public async Task<bool> UpdateRangeAsync(IEnumerable<T> entities)
        {
            db.Set<T>().UpdateRange(entities);
            return await db.SaveChangesAsync() > 0;
        }
        public async Task<bool> AddRangeAsync(IEnumerable<T> entities)
        {
            await db.Set<T>().AddRangeAsync (entities);
            return await db.SaveChangesAsync() > 0;
        }

        public async Task<bool> RemoveRangeAsync(IEnumerable<T> entities)
        {
             db.Set<T>().RemoveRange(entities);
            return await db.SaveChangesAsync() > 0;
        }

        #endregion 异步增删改查方法
    }
}